package edu.yourl.domain;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import edu.yourl.domain.service.ServiceLocator;

public class User extends Gossiper {

	public static final String FAVORITABLE_PREFIX = "@";

	private static final Pattern USER_PATTERN = Pattern.compile("(\\s|^)@\\w+");

	private static final long serialVersionUID = 1L;

	private String password;
	private String name;
	private String nickname;
	private String mail;
	private List<Favoritable> favorites;
		
	public User(String name, String mail, String password, String nickname) {
		super();
		this.name = name;
		this.mail = mail;
		this.nickname = nickname;
		this.seoFriendlyId = slugify(getFavoritableName());
		this.password = password;
		this.favorites = new ArrayList<Favoritable>();
	}
	
	public String getName() {
		return name;
	}
	
	public String getFavoritableName() {
		return FAVORITABLE_PREFIX + nickname;
	}

	public void gossip(String text) {
		this.gossips.add(0, new Gossip(this, text));
	}
	
	public void addFavorite(Favoritable favorite) {
		this.favorites.add(favorite);
	}
	
	public String getMail() {
		return mail;
	}
	
	public String getNickname() {
		return nickname;
	}
	
	public String getPassword() {
		return password;
	}

	public List<Favoritable> getFavorites() {
		return Collections.unmodifiableList(this.favorites);
	}

	public boolean checkPassword(String pass) {
		return password.equals(pass);
	}

	@Override
	public <T> T accept(FavoritableVisitor<T> visitor) {
		return visitor.visit(this);
	}

	public static List<User> extractUsers(String message) {
		List<User> list = new ArrayList<User>();
		Matcher matcher = USER_PATTERN.matcher(message);
		while (matcher.find()) {
			String userText = matcher.group();
			//the @ is cropped out
			userText = userText.trim().substring(1);
			User user = ServiceLocator.getInstance().getUserRepository().getUser(userText);
			if (user != null && !list.contains(user)) {
				list.add(user);
			}
		}
		return list;
	}

	public void modify(String email, String name2, String password2) {
		this.mail = email;
		this.name = name2;
		this.password = password2;
	}

}
